function UserException (value) {
  this.value = value
  this.toString = function () {
    return this.value
  }
}

const Http = {
  post: (url, req, successHandle, errorHandle) => {
    let body = Object.keys(req).map((key) => {
      return encodeURIComponent(key) + '=' + encodeURIComponent(req[key])
    }).join('&')

    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: body
    }).then((response) => {
      if (response.status === 200 || response.status === 201) {
        return response.json()
      } else {
        throw new UserException('HttpRequestError')
      }
    }).then((res) => {
      successHandle && successHandle(res)
    }).catch((err) => {
      console.error(err)
      errorHandle && errorHandle(err)
    })
  },
  get: (url, req, successHandle, errorHandle) => {
    fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }).then((response) => {
      if (response.status === 200 || response.status === 201) {
        return response.json()
      } else {
        throw new UserException('HttpRequestError')
      }
    }).then((res) => {
      successHandle && successHandle(res)
    }).catch((err) => {
      console.error(err)
      errorHandle && errorHandle(err)
    })
  }
}
// const imageUrl = 'http://qqc.hztangong.com'
export default Http

